    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Windows.Forms;
    using Imps.Client;
    using Imps.Client.Core;
    using Imps.Client.Pc;
    using Imps.Client.Utils;
    using Imps.Common;
    using Imps.Utils;

namespace com.hetaoos.FetionSDK.Message
{


    public class ConversationControl : IConversationManager
    {
        private bool _forceToCloseWindow;
        private FetionSDK _frameworkWnd;
        //private ManageForm _scheduleSmsform;
        private bool _showFileType;
        //private GroupSMSForm _smsForm;

        public ConversationControl(FetionSDK framework)
        {
            try
            {
                this._frameworkWnd = framework;
                this.CurrentUser.ConversationManager.FindConversationForm += new EventHandler<FindConversationFormEventArgs>(this.ConversationManager_FindConversationWindow);
                //((Form)framework).FormClosed += new FormClosedEventHandler(this.mainFormclosed);
                this.CurrentUser.StatusChanged += new EventHandler<UserSatusChangedEventArgs>(this.CurrentUser_StatusChanged);
            }
            catch (Exception exception)
            {
                ClientLogger.WriteException(exception);
            }
        }

        public void AddToOwnerEmotion(IWin32Window owner, string shortCut, string name, string filePath)
        {
        }


        /// <summary>
        /// 接收到服务器传过来的消息,通过多种方式查找已存在的聊天窗口，并显示，如果没有，就创建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">
        /// e.Contact  联系人信息
        /// e.Conversation 会话平台
        /// e.Message 消息内容
        /// </param>
        private void ConversationManager_FindConversationWindow(object sender, FindConversationFormEventArgs e)
        {
            try
            {
                if (e.Conversation.Dialogs.Count > 0)
                {
                    IicUri uri = new IicUri(e.Conversation.Dialogs[0].To);
                    if (uri.Type == IicUriType.PersonalGroup)
                    {
                        return;
                    }
                }
                _frameworkWnd.doSDK_ReceiveMessage(this, e.Conversation, e.Contact, e.Message);
            }
            catch (Exception exception)
            {
                ClientLogger.WriteException(exception);
            }

            //MessageBox.Show(e.Message, e.Contact.DisplayName);
            //e.Conversation.CurrentDialog.AsyncSendIm(e.Message);

        }

        //用户状态改变
        private void CurrentUser_StatusChanged(object sender, UserSatusChangedEventArgs e)
        {

        }

        public static bool IsShareContentUrl(Imps.Client.Core.User currentUser, string contactUri, string url)
        {
            Contact contact = currentUser.ContactList.Contacts[contactUri];
            return (((contact != null) && ((contact.Type & ContactType.ImpsContact) != ContactType.None)) && (url.Contains("?") && url.Contains(contact.Uri.Sid.ToString())));
        }

        private void mainFormclosed(object sender, EventArgs e)
        {

        }

        public void SendFile(IWin32Window owner, string contactUri)
        {
            this.StartConversation(owner, ConversationOperation.SendFile, new string[] { contactUri });
        }

        public void SendFile(IWin32Window owner, string contactUri, params string[] filePaths)
        {
            if ((filePaths == null) || (filePaths.Length == 0))
            {
                this.SendFile(owner, contactUri);
            }
            else
            {
                this.StartConversation(owner, ConversationOperation.SendFile, filePaths, false, new string[] { contactUri });
            }
        }

        public void SendFileAfterSelectContacts(IWin32Window owner, List<Contact> list)
        {
            try
            {
                //using (InviteForm form = new InviteForm(this._frameworkWnd, StringTable.Conversation.MsgSelectSendFileContacts, this.CurrentUser.Configuration.SystemSetting.SysConversationSetting.MaxParticipations - 1, true, true, list, null, false, false, false, false))
                //{
                //    form.SelectType = SelectContactsType.MultiConversation;
                //    if ((ControlHelper.ShowDialogCenterOnParent(form, owner, false) == DialogResult.OK) && (form.SelectedContacts.Count != 0))
                //    {
                //        string[] contactUris = new string[form.SelectedContacts.Count];
                //        for (int i = 0; i < form.SelectedContacts.Count; i++)
                //        {
                //            contactUris[i] = form.SelectedContacts[i].Uri.Raw;
                //        }
                //        this.StartConversation(owner, ConversationOperation.SendFile, contactUris);
                //    }
                //}
            }
            catch (Exception exception)
            {
                ClientLogger.WriteException(exception);
            }
        }

        public void SendFileToSelf(IWin32Window owner)
        {
            try
            {
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Title = "打开";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string fileName = dialog.FileName;
                    if (Array.IndexOf<string>((this.CurrentUser.Configuration.SystemSetting.FileShareSetting.ForbiddenShareContentType + ",lnk").ToLower().Split(new char[] { ',', ';' }), Path.GetExtension(fileName).Replace(".", "").ToLower()) >= 0)
                    {
                        //this._frameworkWnd.UnifiedMessageBox.ShowInfo(owner, "该文件可能存在安全隐患，\r\n\r\n为了保护您和您好友的系统安全，将不会发送！");
                    }
                    else
                    {
                        UploadShareContent sc = new UploadShareContent(fileName, this.CurrentUser, true);
                        if (sc.FileSize == 0L)
                        {
                            //this._frameworkWnd.UnifiedMessageBox.ShowInfo(owner, "不允许上传空文件。");
                            sc.Close();
                        }
                        else if (sc.FileSize > this.CurrentUser.Configuration.SystemSetting.FileShareSetting.MaxSizeWhenOffline)
                        {
                            //this._frameworkWnd.UnifiedMessageBox.ShowInfo(string.Format("共享文件最大不能超过{0}", StringHelper.GetFileSize((long)this.CurrentUser.Configuration.SystemSetting.FileShareSetting.MaxSizeWhenOffline)));
                            sc.Close();
                        }
                        else
                        {
                            sc.SendToSelf = true;
                            //SendFileToSelfForm form = new SendFileToSelfForm(sc, this._frameworkWnd);
                            //form.Text = "发送文件";
                            //ControlHelper.ShowFormCenterOnParent(form, this._frameworkWnd.MainWindow);
                            //ThreadPool.QueueUserWorkItem(new WaitCallback(sc.SendFileInThread));
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ClientLogger.WriteException(exception);
            }
        }

        public void ShowCustomEmotionManageForm(IWin32Window owner)
        {

        }

        public static void ShowMessageReceiveNotifyWindow(Form newForm, Contact contact, string message)
        {
            //NotifyWindowEventHandler handler = null;
            //try
            //{
            //    if (contact != null)
            //    {
            //        ReciveMessageNotifyForm notifyWindow = new ReciveMessageNotifyForm(contact, message);
            //        notifyWindow.Cursor = Cursors.Hand;
            //        if (handler == null)
            //        {
            //            handler = delegate
            //            {
            //                if (!newForm.IsDisposed)
            //                {
            //                    newForm.Activate();
            //                    newForm.WindowState = FormWindowState.Normal;
            //                }
            //            };
            //        }
            //        notifyWindow.ContentClick += handler;
            //        NotifyWindowManager.Add(notifyWindow);
            //    }
            //}
            //catch (Exception exception)
            //{
            //    ClientLogger.WriteGeneral("收到消息 弹出爬楼梯窗口失败！", exception.ToString());
            //}
        }

        public void ShowScheduleSmsForm(IWin32Window owner)
        {
            //if ((this._scheduleSmsform == null) || this._scheduleSmsform.IsDisposed)
            //{
            //    this._scheduleSmsform = new ManageForm(this._frameworkWnd);
            //    ControlHelper.ShowFormCenterOnParent(this._scheduleSmsform, owner);
            //    if (this._scheduleSmsform != null)
            //    {
            //        this._scheduleSmsform.Left -= 13;
            //        this._scheduleSmsform.Top -= 0x12;
            //    }
            //}
            //else
            //{
            //    Imps.Client.Utils.Win32.NativeMethods.ShowWindow(this._scheduleSmsform.Handle, 9);
            //    this._scheduleSmsform.Activate();
            //}
        }

        public void StartConversation(IWin32Window owner, ConversationOperation operation, params string[] contactUris)
        {
            this.StartConversation(owner, operation, false, contactUris);
        }

        public void StartConversation(IWin32Window owner, ConversationOperation operation, bool showSelectContactsForm, params string[] contactUris)
        {
            if (this.CurrentUser.Status == UserAccountStatus.Logon)
            {
                if ((contactUris != null) && !showSelectContactsForm)
                {
                    if (((operation == ConversationOperation.SmsChat) && (contactUris.Length == 1)) && (contactUris[0] == this.CurrentUser.Uri.Raw))
                    {
                        List<Contact> list2 = new List<Contact>();
                        Contact item = this.CurrentUser.ContactList.FindOrCreateContact(this.CurrentUser.Uri.Raw, new AsyncBizOperation());
                        list2.Add(item);
                        this.StartMultiSMS(owner, list2);
                    }
                    else
                    {
                        this.StartConversation(owner, operation, null, false, contactUris);
                    }
                }
                else
                {
                    List<Contact> list = null;
                    if (contactUris != null)
                    {
                        list = new List<Contact>();
                        foreach (string str in contactUris)
                        {
                            Contact contact = this.CurrentUser.ContactList.FindOrCreateContact(str, new AsyncBizOperation());
                            if (contact != null)
                            {
                                list.Add(contact);
                            }
                        }
                    }
                    switch (operation)
                    {
                        case ConversationOperation.ImChat:
                            this.StartConversationAfterSelectContacts(owner, list);
                            return;

                        case ConversationOperation.SmsChat:
                            this.StartMultiSMS(owner, list);
                            return;

                        case ConversationOperation.MmsChat:
                            return;

                        case ConversationOperation.SendFile:
                            this.SendFileAfterSelectContacts(owner, list);
                            return;
                    }
                }
            }
        }

        //开始和好友交谈,首先寻找是否已经存在会话，没有就创建
        private void StartConversation(IWin32Window owner, ConversationOperation operation, object context, bool allowStranger, params string[] contactUris)
        {
            try
            {
                //确认用户已经登录
                if ((this.CurrentUser.Status == UserAccountStatus.Logon) && (operation != ConversationOperation.MmsChat))
                {
                    //如果是自己
                    if ((contactUris.Length == 1) && (contactUris[0] == this.CurrentUser.Uri.Raw))
                    {
                        this._frameworkWnd.ShowOptions("PsGeneral");
                    }
                    else
                    {
                        List<Contact> list = new List<Contact>();
                        for (int i = 0; i < contactUris.Length; i++)
                        {
                            //如果不是自己
                            if (!(contactUris[i] == this.CurrentUser.Uri.Raw))
                            {
                                //查找用户
                                Contact item = this.CurrentUser.ContactList.FindOrCreateContact(contactUris[i], new AsyncBizOperation());
                                if (item != null)
                                {
                                    list.Add(item);
                                }
                            }
                        }
                        //群发短信
                        if ((operation == ConversationOperation.SmsChat) && (list.Count > 1))
                        {
                            this.StartMultiSMS(owner, list);
                        }
                        else
                        {
                            if (list.Count > 1)
                            {
                                //去除不支持群聊的
                                for (int j = list.Count - 1; j >= 0; j--)
                                {
                                    if (!list[j].EnableMultiIM)
                                    {
                                        list.Remove(list[j]);
                                    }
                                }
                            }
                            if (list.Count != 0)
                            {
                                Imps.Client.Core.Conversation conversation = null;
                                string to = null;
                                //如果是单聊天对象
                                if (list.Count == 1)
                                {
                                    to = list[0].Uri.Raw;
                                    //枚举对话平台
                                    foreach (Imps.Client.Core.Conversation conversation2 in this.CurrentUser.ConversationManager.Conversations)
                                    {
                                        if (conversation2.CurrentDialog != null)
                                        {
                                            //如果不是多人会话
                                            if (!conversation2.CurrentDialog.IsMulitiConversation)
                                            {
                                                //如果目标对象相同
                                                if (conversation2.CurrentDialog.To == to)
                                                {
                                                    //更新
                                                    conversation = conversation2;
                                                }
                                            }//如果是伪多人会话
                                            else if ((conversation2.CurrentDialog.Participants.Count == 1) && (conversation2.CurrentDialog.Participants[0].Contact.Uri.Raw == to))
                                            {
                                                conversation = conversation2;
                                            }
                                            continue;
                                        }
                                        try
                                        {
                                            if (this.CurrentUser.ConversationManager.Conversations.Contains(conversation))
                                            {
                                                this.CurrentUser.ConversationManager.Conversations.Remove(conversation);
                                            }
                                            conversation = null;
                                            continue;
                                        }
                                        catch (Exception exception)
                                        {
                                            ClientLogger.WriteException(exception);
                                            continue;
                                        }
                                    }
                                }
                                //如果会话平台找不到,就创建
                                if (conversation == null)
                                {
                                    //哈哈，在这里创建会话平台
                                    conversation = this.CurrentUser.ConversationManager.OpenConversation(to, list);
                                }
                                conversation.CurrentDialog.AsyncSendIm("What Can I Do For You??");
                                //如果操作是发送文件
                                if (operation == ConversationOperation.SendFile)
                                {

                                }

                            }
                        }
                    }
                }
            }
            catch (Exception exception2)
            {
                ClientLogger.WriteException(exception2);
            }
        }

        public void StartConversationAfterSelectContacts(IWin32Window owner, List<Contact> list)
        {
            try
            {
                //using (InviteForm form = new InviteForm(this._frameworkWnd, StringTable.Conversation.MsgSelectConversationContacts, this.CurrentUser.Configuration.SystemSetting.SysConversationSetting.MaxParticipations - 1, true, true, list, null, false, false, false, false))
                //{
                //    form.SelectType = SelectContactsType.MultiConversation;
                //    if ((ControlHelper.ShowDialogCenterOnParent(form, owner, false) == DialogResult.OK) && (form.SelectedContacts.Count != 0))
                //    {
                //        string[] contactUris = new string[form.SelectedContacts.Count];
                //        for (int i = 0; i < form.SelectedContacts.Count; i++)
                //        {
                //            contactUris[i] = form.SelectedContacts[i].Uri.Raw;
                //        }
                //        this.StartConversation(owner, ConversationOperation.ImChat, null, false, contactUris);
                //    }
                //}
            }
            catch (Exception exception)
            {
                ClientLogger.WriteException(exception);
            }
        }

        public void StartMultiSMS(IWin32Window owner)
        {
            this.StartMultiSMS(owner, null);
        }

        public void StartMultiSMS(IWin32Window owner, List<Contact> list)
        {
            //FormClosedEventHandler handler = null;
            //if (((this._smsForm == null) || this._smsForm.IsDisposed) || (list != null))
            //{
            //    if (this._smsForm != null)
            //    {
            //        this._smsForm.Close();
            //    }
            //    this._smsForm = new GroupSMSForm(this.FrameworkWnd, list);
            //    if (handler == null)
            //    {
            //        handler = delegate
            //        {
            //            this._smsForm = null;
            //        };
            //    }
            //    this._smsForm.FormClosed += handler;
            //    ControlHelper.ShowFormCenterOnParent(this._smsForm, owner);
            //}
            //else
            //{
            //    Imps.Client.Utils.Win32.NativeMethods.ShowWindow(this._smsForm.Handle, 9);
            //    this._smsForm.Activate();
            //}
        }

        public void StartStrangerConversation(IWin32Window owner, string uri)
        {
            this.StartConversation(owner, ConversationOperation.ImChat, null, true, new string[] { uri });
        }

        internal Imps.Client.Core.User CurrentUser
        {
            get
            {
                return this._frameworkWnd.AccountManager.CurrentUser;
            }
        }

        public bool ForceToCloseWindow
        {
            get
            {
                return this._forceToCloseWindow;
            }
            set
            {
                this._forceToCloseWindow = value;
            }
        }

        internal IFrameworkWindow FrameworkWnd
        {
            get
            {
                return this._frameworkWnd;
            }
        }

        internal bool ShowFileType
        {
            get
            {
                return this._showFileType;
            }
            set
            {
                this._showFileType = value;
            }
        }


        public void SendIM(Contact user, string msg)
        {

            List<Contact> list = new List<Contact>();
            list.Add(user);
            SendIM(list, msg);
        }

        public void SendIM(List<Contact> list, string msg)
        {
            try
            {
                //确认用户已经登录
                if (this.CurrentUser.Status == UserAccountStatus.Logon)
                {
                    //如果是自己
                    if ((list.Count == 1) && (list[0].Uri.Raw == this.CurrentUser.Uri.Raw))
                    {
                        //this._frameworkWnd.ShowOptions("PsGeneral");
                    }
                    else
                    {

                        if (list.Count > 1)
                        {
                            //去除不支持群聊的
                            for (int j = list.Count - 1; j >= 0; j--)
                            {
                                if (!list[j].EnableMultiIM)
                                {
                                    list.Remove(list[j]);
                                }
                            }
                        }
                        if (list.Count != 0)
                        {
                            Imps.Client.Core.Conversation conversation = null;
                            string to = null;
                            //如果是单聊天对象
                            if (list.Count == 1)
                            {
                                to = list[0].Uri.Raw;
                                //枚举对话平台
                                foreach (Imps.Client.Core.Conversation conversation2 in this.CurrentUser.ConversationManager.Conversations)
                                {
                                    if (conversation2.CurrentDialog != null)
                                    {
                                        //如果不是多人会话
                                        if (!conversation2.CurrentDialog.IsMulitiConversation)
                                        {
                                            //如果目标对象相同
                                            if (conversation2.CurrentDialog.To == to)
                                            {
                                                //更新
                                                conversation = conversation2;
                                            }
                                        }//如果是伪多人会话
                                        else if ((conversation2.CurrentDialog.Participants.Count == 1) && (conversation2.CurrentDialog.Participants[0].Contact.Uri.Raw == to))
                                        {
                                            conversation = conversation2;
                                        }
                                        continue;
                                    }
                                    try
                                    {
                                        if (this.CurrentUser.ConversationManager.Conversations.Contains(conversation))
                                        {
                                            this.CurrentUser.ConversationManager.Conversations.Remove(conversation);
                                        }
                                        conversation = null;
                                        continue;
                                    }
                                    catch (Exception exception)
                                    {
                                        ClientLogger.WriteException(exception);
                                        continue;
                                    }
                                }
                            }
                            //如果会话平台找不到,就创建
                            if (conversation == null)
                            {
                                //哈哈，在这里创建会话平台
                                conversation = this.CurrentUser.ConversationManager.OpenConversation(to, list);
                            }
                            conversation.CurrentDialog.AsyncSendIm(msg);

                        }

                    }
                }
            }
            catch (Exception exception2)
            {
                ClientLogger.WriteException(exception2);
            }
        }
    }
}
